/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.Main;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.util.StringTokenizer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;

/**
 *
 * @author Kumori
 */
public class test {/*Language test*/


    public static BufferedReader read(String url) throws Exception {
        return new BufferedReader(
                new InputStreamReader(
                new URL(url).openStream()));
    }

    public static void main(String[] args) throws Exception {
   	   //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
			public void run() {
                createAndShowGUI();
            }
        });
    
      	
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
        int numPairs = labels.length;
        //Create and populate the panel.
        final JPanel p = new JPanel(new SpringLayout());
        for (int i = 0; i < numPairs; i++) {
            JLabel l = new JLabel(labels[i], SwingConstants.TRAILING);
            p.add(l);
            JTextField textField = new JTextField(10);
            l.setLabelFor(textField);
            p.add(textField);
        }
        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("Ok button was clicked!");
				Component[] listCompo= p.getComponents();
				Component currentCompo = null;
				for (int i= 0;i<listCompo.length;i++){
					currentCompo = listCompo[i];
					if (currentCompo instanceof JTextField)
					{
						JTextField j = (JTextField) currentCompo; 
						System.out.println(j.getText());
					}
				}
			}
		});
		JButton cancelButton = new JButton("Cancel");

		cancelButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("Cancel button was clicked!");
				System.exit(0);
			}
		});
        p.add(okButton);
        p.add(cancelButton);
        //Lay out the panel.
        SpringUtilities.makeCompactGrid(p,
                                        numPairs+1, 2, //rows, cols
                                        6, 6,        //initX, initY
                                        6, 6);       //xPad, yPad
        
        //Create and set up the window.
        JFrame frame = new JFrame("SpringForm");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Set up the content pane.
        p.setOpaque(true);  //content panes must be opaque
        frame.setContentPane(p);
 
        //Display the window.
        frame.pack();
        //frame.setSize(280, 180);
        frame.setVisible(true);
        
    }
    public static void socketChannel(String url) throws Exception {
        URL u = new URL(url);
        String host = u.getHost();
        int port = 80;
        String file = "/";

        SocketAddress remote = new InetSocketAddress(host, port);
        SocketChannel channel = SocketChannel.open(remote);
        FileOutputStream out = new FileOutputStream("yourfile.htm");
        FileChannel localFile = out.getChannel();

        String request = "GET " + file + " HTTP/1.1\r\n" + "User-Agent: HTTPGrab\r\n"
                + "Accept: text/*\r\n" + "Connection: close\r\n" + "Host: " + host + "\r\n" + "\r\n";

        ByteBuffer header = ByteBuffer.wrap(request.getBytes("US-ASCII"));
        channel.write(header);

        ByteBuffer buffer = ByteBuffer.allocate(8192);
        while (channel.read(buffer) != -1) {
            buffer.flip();
            localFile.write(buffer);
            buffer.clear();
        }

        localFile.close();
        channel.close();
    }

    public static void readUrl(String str1) throws Exception {
        BufferedReader reader = read(str1);
        String line = reader.readLine();
        String db = "";
        String str = "";
        System.out.println(db);
        int i = 0;
        while (line != null) {
            i++;
            if (i == 55) {
                str = line;
                break;
            } else {
                line = reader.readLine();
            }
        }
        getInfo(str);
    }

    ;
    private static void getInfo(String str) {
        int i = 0;
        String[] result = null;
        String tag = "";
        System.out.println(str.length());
        int firstIdx = str.indexOf("<");
        int lastIdx = str.indexOf(">");
        tag = str.substring(firstIdx, lastIdx + 1);
        str = str.replaceAll(tag, "");
        //System.out.print(str);
        //  try{
        while (i < str.length()) {
            i++;
            firstIdx = str.indexOf("<");
            lastIdx = str.indexOf(">");
            if ((firstIdx != -1) && (lastIdx != -1)) {
                tag = str.substring(firstIdx, lastIdx + 1);
                str = str.replaceAll(tag, ";");
            }

        }
        StringTokenizer strTok = new StringTokenizer(str, ";");
        result = new String[strTok.countTokens()];
        int index = 0;
        String path = "D:\\My Books\\My Document\\Test Data";
        //String path = "E:\\Dropbox\\Dropbox\\Data";
        String nameOfFile = "KQ.htm";
        File file = new File(path, nameOfFile);
        outputToFile(strTok, file);
        // System.out.println(strTok.nextToken());
    }

    private static void outputToFile(StringTokenizer strTok, File file) {
        try {
            // Create file 
            FileWriter fstream = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(fstream);
            while (strTok.hasMoreTokens()) {
                //result[index] = strTok.nextToken();
                //  index++;      
                out.write(strTok.nextToken() + "\n");
            }
            //Close the output stream
            out.close();

        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}
